package com.radon.position.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.csvreader.CsvReader;
import com.csvreader.CsvWriter;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.List;

public class CSVUtil {

    public static JSONArray read(String filePath){
        JSONArray jsonArray = new JSONArray();
        try {
            // 创建CSV读对象
            CsvReader csvReader = new CsvReader(filePath,',',Charset.forName("utf-8"));
            // 跳过表头
            csvReader.readHeaders();
            String[] head = csvReader.getHeaders(); //获取表头

            while (csvReader.readRecord()){
                // 读一整行
                //String utf8 = new String(gbk.getBytes("gbk"), "utf-8");
               /* System.out.println(csvReader.getRawRecord().toString());
                // 读这行的某一列
                System.out.println(csvReader.get("name"));*/
                JSONObject jsonObject = new JSONObject();
                for (int i = 0; i < head.length; i++)
                {
                    jsonObject.put(head[i],csvReader.get(head[i]));
                    //System.out.println(jsonObject.toJSONString());
                }
                jsonArray.add(jsonObject);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return jsonArray;
    }

    public static void write(String filePath, List<String[]> content, String[] headers){

        try {
            // 创建CSV写对象
            CsvWriter csvWriter = new CsvWriter(filePath,',', Charset.forName("GBK"));
            //CsvWriter csvWriter = new CsvWriter(filePath);
            // 写表头
            csvWriter.writeRecord(headers);
            for (Iterator<String[]> iterator = content.iterator(); iterator.hasNext(); ) {
                String[] next =  iterator.next();
                csvWriter.writeRecord(next);
            }
            csvWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
